package com.susallwave.srcb.serviceimpl.sys;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.susallwave.srcb.entity.sys.UserRole;
import com.susallwave.srcb.mapper.sys.UserRoleMapper;
import com.susallwave.srcb.response.Result;
import com.susallwave.srcb.service.sys.UserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户角色关系表 服务实现类
 * </p>
 *
 * @author MyBatisPlusGenerator
 * @since 2025-07-20
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Override
    public List<UserRole> userRoles(String userAcct) {
        return this.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserAcct,userAcct));
    }

    @Override
    public Result<IPage<UserRole>> listRoles(int pageNum, int pageSize, String userAcct, String roleCode) {
        Page<UserRole> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<UserRole> qw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(userAcct)) {
            qw.eq(UserRole::getUserAcct, userAcct);
        }
        if (StringUtils.isNotBlank(roleCode)) {
            qw.eq(UserRole::getRoleCode, roleCode);
        }
        return Result.success(this.page(page,qw));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> setUserRoles(String userAcct, List<String> roleCodes) {
        // 先删除旧记录
        this.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserAcct, userAcct));
        // 插入新记录
        List<UserRole> list = roleCodes.stream().map(roleCode -> {
            UserRole ur = new UserRole();
            ur.setUserAcct(userAcct);
            ur.setRoleCode(roleCode);
            return ur;
        }).collect(Collectors.toList());
        this.saveBatch(list);
        return Result.success();
    }
}
